/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.wlhy.report.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ReportPlatformEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.third.jg.report.freight.information.constant.enums.ReportDocTypeEnum;
import org.jeecg.modules.third.jg.report.freight.information.dto.AppInfoDTO;
import org.jeecg.modules.third.jg.report.freight.information.dto.DriverDTO;
import org.jeecg.modules.third.jg.report.freight.information.dto.VehicleDTO;
import org.jeecg.modules.third.jg.report.freight.information.dto.financial.FinancialDTO;
import org.jeecg.modules.third.jg.report.freight.information.dto.shippingnote.ShippingNoteDTO;
import org.jeecg.modules.third.jg.report.freight.information.model.R;
import org.jeecg.modules.third.jg.report.freight.information.service.YunnanReportPlatformService;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.company.entity.HyCompanyConfig;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriverReport;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverReportService;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleReport;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleType;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleReportService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.report.IReportService;
import org.jeecg.modules.wlhy.shipping.constant.ShippingPayStatus;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class YunnanReportService implements IReportService {

    @Resource
    private BaseReportService baseReportService;

    @Resource
    private IHyDriverService driverService;

    @Resource
    private IHyVehicleService vehicleService;

    @Resource
    private IHyDriverReportService hyDriverReportService;

    @Resource
    private IHyVehicleReportService vehicleReportService;

    @Autowired
    private YunnanReportPlatformService yunnanReportPlatformService;

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Autowired
    private IHyShippingNoteBillService hyShippingNoteBillService;

    @Override
    public ReportPlatformEnum getReportType() {
        return ReportPlatformEnum.REPORT_PLATFORM_YUNNAN;
    }

    @Override
    public void checkReport() {
        //云南监管平台
        if(!HyCfgUtil.isUsed2("yunnan_report")){
            throw new JeecgBootException("云南监管平台未配置参数!");
        }
    }

    @Override
    public Result setReportInfo(HyCompanyConfig hyCompanyConfig) {

        if (StrUtil.isEmpty(hyCompanyConfig.getReportUrl()) || StrUtil.isEmpty(hyCompanyConfig.getReportUsername())
         || StrUtil.isEmpty(hyCompanyConfig.getReportPassword()) || StrUtil.isEmpty(hyCompanyConfig.getReportPublickey())) {
            return Result.error("云南监管平台未配置参数!");
        }

        this.yunnanReportPlatformService.setReportInfo(hyCompanyConfig.getReportUrl(),
                hyCompanyConfig.getReportUsername(),
                hyCompanyConfig.getReportPassword(),
                hyCompanyConfig.getReportPublickey(),
                hyCompanyConfig.getReportAppid(),
                hyCompanyConfig.getReportAppkey(),
                hyCompanyConfig.getReportAppsender(),
                hyCompanyConfig.getReportApprelease());
        return Result.ok("设置成功");
    }

    @Override
    public AppInfoDTO getAppInfo() {
        return this.yunnanReportPlatformService.getAppInfo();
    }

    @Override
    public Result reportShippingNote(HyShippingNote hyShippingNote) {
        Result result = checkDriverAndVehicle(hyShippingNote);
        if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
            return result;
        }

        return this.uploadYunnanShippingNote(hyShippingNote);
    }

    @Override
    public Result reportCapitalFlow(HyShippingNote hyShippingNote) {
        Result result = checkDriverAndVehicle(hyShippingNote);
        if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
            return result;
        }

        return this.uploadYunnanCapitalFlow(hyShippingNote.getId());
    }

    //上报运单和资金流水前，先确认司机、车辆的上传状态
    private Result checkDriverAndVehicle(HyShippingNote hyShippingNote) {

        String driverId = hyShippingNote.getDriverId();
        String vehicleId = hyShippingNote.getVehicleId();
        if (StrUtil.isEmpty(driverId)) {
            return Result.error("当前运单司机信息不存在");
        }

        if (StrUtil.isEmpty(vehicleId)) {
            return Result.error("当前运单车辆信息不存在");
        }

        //自动上报司机和车辆配置
        String autoUpload = HyCfgUtil.getCfgItem2("yunnan_report","auto_upload");
        boolean bDriverUploadStatus = this.hyDriverReportService.checkUploadStatus(driverId, hyShippingNote.getCompanyId(),
                ReportPlatformEnum.REPORT_PLATFORM_YUNNAN.getCode());
        if (!bDriverUploadStatus) {
            if (StrUtil.isEmpty(autoUpload) || !autoUpload.equals("1")) {
                return Result.error("请先同步司机数据");
            }
            log.warn("司机未上报云南监管，开始同步司机数据, 司机ID：{}", driverId);
            Result dResult = this.reportDriver(driverId, hyShippingNote.getCompanyId());
            if (!dResult.getCode().equals(CommonConstant.SC_OK_200)) {
                return dResult;
            }
        }

        boolean bVehicleUploadStatus = this.vehicleReportService.checkUploadStatus(vehicleId, hyShippingNote.getCompanyId(),
                ReportPlatformEnum.REPORT_PLATFORM_YUNNAN.getCode());
        if (!bVehicleUploadStatus) {
            if (StrUtil.isEmpty(autoUpload) || !autoUpload.equals("1")) {
                return Result.error("请先同步车辆数据");
            }
            log.warn("车辆未上报云南监管，开始同步车辆数据, 车辆ID：{}", vehicleId);
            Result vResult = this.reportVehicle(vehicleId, hyShippingNote.getCompanyId());
            if (!vResult.getCode().equals(CommonConstant.SC_OK_200)) {
                return vResult;
            }
        }

        return Result.OK();
    }


    public Result uploadYunnanCapitalFlow(String shippingId){

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("shipping_id", shippingId);
        List<HyShippingNoteBill> shippingNoteBills = this.hyShippingNoteBillService.list(queryWrapper);

        if (CollectionUtils.isEmpty(shippingNoteBills)) {
            throw new JeecgBootException("未找到对应数据");
        }

        HyShippingNote hyShippingNote = this.hyShippingNoteService.getById(shippingId);
        if (!ShippingPayStatus.支付完成.getValue().equals(hyShippingNote.getShippingPayStatus())) {
            return Result.error("该运单未支付完成，不能上报");
        }
        FinancialDTO financialDTO = this.baseReportService.getFinancialDTO(shippingNoteBills,hyShippingNote);
        String jsonString = JSONObject.toJSONString(financialDTO);
        String reportDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_ZJ.getCode();
        ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reportDocType);
        try {
            String reportResult = this.yunnanReportPlatformService.sendReport(reportDocTypeEnum,jsonString);
            if(StringUtils.isNotEmpty(reportResult)){
                R result = JSON.parseObject(reportResult, R.class);
                boolean res =  result.getCode() == 1001 && result.isSuccess() ?  true : false;
                for(HyShippingNoteBill shippingNoteBillDb :  shippingNoteBills){
                    shippingNoteBillDb.setUploadStatus(res ?  "1" : "2");
                    shippingNoteBillDb.setUploadDate(new Date());
                    shippingNoteBillDb.setReportFailureReason(res ?  "" : result.getMsg()+result.getData());
                    shippingNoteBillDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_YUNNAN.getCode());
                }
                this.hyShippingNoteBillService.updateBatchById(shippingNoteBills);
                return res ? Result.OK("上报成功") : Result.error(result.getMsg());
            }
        }catch (Exception e){
            for(HyShippingNoteBill shippingNoteBillDb :  shippingNoteBills){
                shippingNoteBillDb.setUploadStatus("2");
                shippingNoteBillDb.setUploadDate(new Date());
                shippingNoteBillDb.setReportFailureReason(e.getMessage());
                shippingNoteBillDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_YUNNAN.getCode());
            }
            this.hyShippingNoteBillService.updateBatchById(shippingNoteBills);
        }

        return Result.error("向监管平台发送资金流水数据失败");
    }

    /**
     * 云南平台上报电子运单
     *
     * @param hyShippingNote
     * @return
     */
    public Result uploadYunnanShippingNote(HyShippingNote hyShippingNote) {
        HyShippingNote ShippingNoteDb = hyShippingNoteService.getById(hyShippingNote.getId());
        if (ShippingNoteDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        if ("1".equals(ShippingNoteDb.getUploadStatus())){
            return Result.error("该运单已上报，请勿重复上报");
        }

        //时效判断 运单生成时间<运单发货时间<运单实际收货时间
        if (ShippingNoteDb.getStatusDtReceive().after(ShippingNoteDb.getStatusDtLoading())
                || ShippingNoteDb.getStatusDtLoading().after(ShippingNoteDb.getStatusDtUnloading())) {
            ShippingNoteDb.setUploadStatus("2");
            ShippingNoteDb.setUploadDate(new Date());
            ShippingNoteDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_YUNNAN.getCode());
            ShippingNoteDb.setReportFailureReason("该运单时效存在错误，必须满足:运单创建时间<运单装货时间<运单卸货时间。");
            this.hyShippingNoteService.updateById(ShippingNoteDb);
            return Result.error("该运单时效存在错误，必须满足:运单接单时间<运单装货时间<运单卸货时间。");
        }

        //超载判断
        HyVehicle hyVehicle = this.vehicleService.getById(ShippingNoteDb.getVehicleId());
        if (ShippingNoteDb.getGoodsWeightLoading().compareTo(hyVehicle.getVehicleTonnage()) > 0 ) {
            ShippingNoteDb.setUploadStatus("2");
            ShippingNoteDb.setUploadDate(new Date());
            ShippingNoteDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_YUNNAN.getCode());
            ShippingNoteDb.setReportFailureReason("货物重量超过车辆核定载质量，货物重量: "+ShippingNoteDb.getGoodsWeightLoading()+"车辆核定载质量:"+hyVehicle.getVehicleTonnage());
            this.hyShippingNoteService.updateById(ShippingNoteDb);
            log.error("云南监管上报超载 货物重量 {} > 核定载质量 {}", ShippingNoteDb.getGoodsWeightLoading(), hyVehicle.getVehicleTonnage());
            return Result.error("货物重量超过车辆核定载质量，货物重量:" + ShippingNoteDb.getGoodsWeightLoading() + " ,车辆核定载质量:" + hyVehicle.getVehicleTonnage());
        }


        ShippingNoteDTO shippingNoteDTO = this.baseReportService.shippingNoteTOShippingNoteDTO(ShippingNoteDb, hyShippingNote.getCompanyId());
        String jsonString = JSONObject.toJSONString(shippingNoteDTO);
        String reportDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_YD.getCode();
        ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reportDocType);

        try{
            String reportResult = this.yunnanReportPlatformService.sendReport(reportDocTypeEnum, jsonString);
            if (StringUtils.isNotEmpty(reportResult)) {
                R result = JSON.parseObject(reportResult, R.class);
                boolean res = result.getCode() == 1001 && result.isSuccess() ? true : false;
                ShippingNoteDb.setUploadStatus(res ? "1" : "2");
                ShippingNoteDb.setUploadDate(new Date());
                ShippingNoteDb.setReportFailureReason(res ? "" : result.getMsg()+result.getData());
                ShippingNoteDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_YUNNAN.getCode());
                hyShippingNoteService.updateById(ShippingNoteDb);
                return res ? Result.OK("上报成功") : Result.error(result.getMsg());
            }
        }catch (Exception e){
            ShippingNoteDb.setUploadStatus("2");
            ShippingNoteDb.setUploadDate(new Date());
            ShippingNoteDb.setReportFailureReason(e.getMessage());
            ShippingNoteDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_YUNNAN.getCode());
            hyShippingNoteService.updateById(ShippingNoteDb);
        }

        return Result.error("向监管平台发送运单数据失败");
    }


    public Result reportVehicle(String vehicleId, String companyId) {
        HyVehicle hyVehicleDb = vehicleService.getById(vehicleId);
        if (hyVehicleDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        HyVehicleReport hyVehicleReport = new HyVehicleReport();

        if (StringUtils.isEmpty(hyVehicleDb.getRoadTransportNumber())) {
            return Result.error("车辆道路运输证不能为空！");
        }

//      if(!vehicleService.checkRTCNoV2(hyVehiclDb)){
//          throw new JeecgBootException("车辆道路运输证号不正确或者已过期，请修改后重新上传！");
//       }

        HyVehicleType hyVehicleType = vehicleService.getHyVehicleType(hyVehicleDb.getVehicleType());
        if (hyVehicleType == null) {
            return Result.error("车辆类型不存在,修改后请重新上报！");
        }
        hyVehicleDb.setVehicleType(hyVehicleType.getValue());
        VehicleDTO vehicleDTO = this.baseReportService.hyVehicleDTOTOVehicleDTO(hyVehicleDb);
        String jsonString = JSONObject.toJSONString(vehicleDTO);
        String reportDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_CL.getCode();
        ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reportDocType);

        try {
            String reportResult = this.yunnanReportPlatformService.sendReport(reportDocTypeEnum, jsonString);
            if (StringUtils.isNotEmpty(reportResult)) {
                R result = JSON.parseObject(reportResult, R.class);
                boolean bResultFlag = result.getCode() == 1001 && result.isSuccess() ? true : false;
                hyVehicleReport.setVehicleId(vehicleId);
                hyVehicleReport.setCompanyId(companyId);
                hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_HUBEI.getCode());
                hyVehicleReport.setVehicleUploadStatus(bResultFlag ? "1" : "2");
                hyVehicleReport.setUploadDate(new Date());
                hyVehicleReport.setVehicleReportFailureReason(result.getMsg() + result.getData());

                boolean bUpdate = this.vehicleService.updateJgUploadStatusById(vehicleId, hyVehicleReport.getVehicleUploadStatus());
                log.info("云南监管更新车辆上报回执信息, {}, {}, {}", bUpdate, bResultFlag, result.getMsg());
                this.vehicleReportService.saveVehicleReport(hyVehicleReport);

                return bResultFlag ? Result.OK("上报成功") : Result.error(result.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.error("向监管平台发送车辆数据失败");
    }


    public Result reportDriver(String driverId, String companyId) {
        HyDriver hyDriverDb = driverService.getById(driverId);
        if (hyDriverDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        HyDriverReport hyDriverReport = new HyDriverReport();

        //人员从业资格证验证
//      if(!driverService.checkQualificationV2(hyDriverDb)){
//           throw new JeecgBootException("人员从业资格证验证号不正确或者已过期，请修改后重新上传！");
//      }

        DriverDTO driverDTO = this.baseReportService.hyDriverTODriverDTO(hyDriverDb);
        String jsonString = JSONObject.toJSONString(driverDTO);
        String reportDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_JSY.getCode();
        ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reportDocType);

        try {
            String reportResult = this.yunnanReportPlatformService.sendReport(reportDocTypeEnum, jsonString);
            if (StringUtils.isNotEmpty(reportResult)) {
                R result = JSON.parseObject(reportResult, R.class);
                boolean bResultFlag = result.getCode() == 1001 && result.isSuccess() ? true : false;
                hyDriverReport.setDriverId(driverId);
                hyDriverReport.setCompanyId(companyId);
                hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_HUBEI.getCode());
                hyDriverReport.setDriverUploadStatus(bResultFlag ? "1" : "2");
                hyDriverReport.setUploadDate(new Date());
                hyDriverReport.setDriverReportFailureReason(result.getMsg() + result.getData());

                boolean bUpdate = this.driverService.updateJgUploadStatusById(driverId, hyDriverReport.getDriverUploadStatus());
                log.info("云南监管更新司机上报回执信息, {}, {}, {}", bUpdate, bResultFlag, result.getMsg());
                this.hyDriverReportService.saveDriverReport(hyDriverReport);

                return bResultFlag ? Result.OK("上报成功") : Result.error(result.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.error("向监管平台发送司机数据失败");
    }

}
